package service

import (
	"beesoft.ink/application/garage/app/g"
	"beesoft.ink/application/garage/app/model"
	"github.com/labstack/echo/v4"
	"gorm.io/gorm/clause"
)

var Category = category{}

type category struct{}

func (r category) List(ctx echo.Context, req *model.CategoryListReq) []model.Category {
	var items []model.Category

	g.DB().
		Where("type", req.Type).
		Order(clause.OrderByColumn{
			Column: clause.Column{
				Name: "sort",
			},
			Desc: false,
		}).
		// Order(clause.OrderByColumn{
		// 	Column: clause.Column{
		// 		Name: req.Order,
		// 	},
		// 	Desc: req.OrderDirection,
		// }).
		// Offset((req.Page - 1) * req.PageSize).
		// Limit(req.PageSize).
		Find(&items)

	return items
}
func (r category) Show(ctx echo.Context) (*model.Category, error) {
	id := ctx.Param("id")

	var item *model.Category
	if err := g.DB().First(&item, id).Error; err != nil {
		return nil, err
	}

	return item, nil
}
func (r category) Store(ctx echo.Context) error {
	item := new(model.Category)

	if err := ctx.Bind(item); err != nil {
		return err
	}

	g.DB().Create(item)

	return nil
}
func (r category) Update(ctx echo.Context) error {
	id := ctx.Param("id")

	var item *model.Category
	if err := g.DB().First(&item, id).Error; err != nil {
		return err
	}

	if err := ctx.Bind(&item); err != nil {
		return err
	}

	g.DB().Save(&item)

	return nil
}
func (r category) Destroy(ctx echo.Context, id uint) error {
	var item *model.Category
	if err := g.DB().First(&item, id).Error; err != nil {
		return err
	}

	g.DB().Delete(&item)

	return nil
}
